import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
import Cookies from 'js-cookie'
import { ElMessageBox } from 'element-plus'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

let _temp = 1

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    /* has token*/
    if(window.location?.search?.slice(1)?.split('=')[1]){
      if(Cookies.get('ticket')){
        if(window.location?.search?.slice(1)?.split('=')[1] !== Cookies.get('ticket') && _temp === 1){
          _temp ++
            useUserStore().login_sso(window.location?.search?.slice(1)?.split('=')[1]).then((res) => {
              // router.push({ path: "/" })
              NProgress.done()
            }).catch(() => {
              ElMessageBox.alert('您暂无权限，请联系管理员，谢谢！', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              }).then(() => {
                console.log('请联系管理员!')
              }).catch(() => { })
            })
        }
      }
    }

    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true
        useUserStore().getInfo().then(() => {
          isRelogin.show = false
          usePermissionStore().generateRoutes().then(accessRoutes => {
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) {
                router.addRoute(route)
              }
            })
            next({ ...to, replace: true })
          })
        }).catch(err => {
          useUserStore().logOut().then(() => {
            ElMessage.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if(window.location?.search?.slice(1)?.split('=')[0] === 'ticket'){
        useUserStore().login_sso(window.location?.search?.slice(1)?.split('=')[1]).then((res) => {
          router.push({ path: "/" })
          NProgress.done()
        }).catch(() => {
          ElMessageBox.alert('您暂无权限，请联系管理员，谢谢！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            console.log('请联系管理员!')
          }).catch(() => { })
        })
      } else {
        next(`/login?redirect=${to.fullPath}`)
      }

    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
